<style lang="scss" scoped>
::v-deep .el-input__inner {
  height: 22px;
}
</style>

<template>
  <el-popover :width="width" :disabled="disabled" trigger="click">
    <!-- 需要表单则自定义 预留了表单插槽 -->
    <slot name="searchform"></slot>
    <el-table :height="height" :data="pagination ? paginationData : data" highlight-current-row @row-click="clickRow" border>
      <el-table-column
        v-for="(item, index) in column"
        show-overflow-tooltip
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :type="item.type"
        :align="item.align || 'center'"
        >
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="pagination"
      class="pagination"
      small
      background
      ref="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="Pagination.currentPage"
      :page-sizes="Pagination.pageSizeList"
      :page-size="Pagination.pageSize"
      :layout="Pagination.layout"
      :total="Pagination.total"
    ></el-pagination>
    <el-input clearable :placeholder="placeholder" slot="reference" :value="value"></el-input>
  </el-popover>
</template>

<script>
import paginationMixin from '@/mixins/pagination'

export default {
  mixins: [paginationMixin],
  name: 'el-select-table',
  data () {
    return {
      paginationData: [], // 分页时 table 的数据源
      Pagination: {
        layout: 'sizes, prev, next, jumper, total'
      }
    }
  },
  props: {
    pagination: {
      type: Boolean,
      default: false
    }, // 是否启用分页 启用后 data 属性失效，采用 getData 方法获取数据源
    width: {
      type: [String, Number],
      default: '420'
    },
    height: {
      type: Number,
      default: 300
    },
    data: {
      type: Array,
      default () { return [] }
    }, // 表格数据
    column: {
      type: Array,
      required: true
    }, // 表格列的数据 [{ prop: '', label: '' }]
    value: {
      type: String
    }, // 输入框显示的值
    disabled: {
      type: Boolean,
      default: false
    }, // 是否禁用
    placeholder: {
      type: String,
      default: ''
    },
    clearable: {
      type: Boolean,
      default: false
    },
    getData: {
      type: Function,
      default: () => {
        console.warn('需要传入 getData 方法，该方法有两个参数：currentPage, pageSize')
        console.warn('getData 方法同时需要返回一个 Promise 携带参数格式如下：{ data: [], total: 0 }')
        return Promise.resolve({
          data: [],
          total: 0
        })
      }
    }
  },
  mounted () {
    // 如果有分页的话使用分页的数据
    if (this.pagination) {
      this.refreshList()
    }
  },
  methods: {
    // 单击某一行触发的事件
    clickRow (row, column, event) {
      this.$emit('row-click', row, column, event)
      // this.disabled = true
    },
    getList (currentPage, pageSize, updateTotal) {
      this.getData(currentPage, pageSize).then(res => {
        this.paginationData = res.data
        updateTotal(Number(res.total))
      })  
    }
  }
}
</script>
